package com.book.service.impl;

import cn.hutool.core.date.DateUtil;
import com.book.core.exception.FileUpException;
import com.book.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 使用本地文件存储的实现
 *
 * @author hongmizfb
 * @date 2025/05/10
 */
@Service("localFileService")
@Primary
public class LocalFileServiceImpl implements FileService {
    @Value("${app.file.upload-path}")
    private String filePath;
    @Value("${app.file.prefix}")
    private  String prefix;

    @Override
    public String uploadFile(MultipartFile file, String bucket) {
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException("获取文件输入流失败", e);
        }
        // 获取时间作为文件名
        String time = DateUtil.format(DateUtil.date(), "yyyy-MM");
        String savePath = filePath + "/" + bucket + "/" + time + "/" + originalFilename;
        try {
            Path directory = Paths.get(filePath, bucket, time);
            Files.createDirectories(directory);
            OutputStream fileOutputStream = Files.newOutputStream(Paths.get(savePath));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            fileOutputStream.close();

        } catch (IOException e) {
            // 确保流被关闭
            try {
                inputStream.close();
            } catch (IOException ex) {
                e.addSuppressed(ex);
            }
            throw new FileUpException("上传失败: " + savePath);
        }

        return prefix + "/" + bucket + "/" + time + "/" + originalFilename;
    }
}
